import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

import 'models/bt_order.dart';
import 'models/bt_post.dart';

class DatabaseHelper {
  late final Database _database;

  DatabaseHelper._internal();

  factory DatabaseHelper() => _instance;

  static final DatabaseHelper _instance = DatabaseHelper._internal();

  Database get database => _database;

  Future<void> initDatabase() async {
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'brew_tunes.db');

    _database = await openDatabase(path, version: 2, onCreate: (Database db, int version) async {
      await db.execute('''
        create table $tablePost (
          $columnAuthorId text primary key,
          $columnAuthorName text not null,
          $columnAvatar text not null,
          $columnTitle text not null,
          $columnSubTitle text not null,
          $columnContent text not null,
          $columnFollowed integer not null,
          $columnCover text not null,
          $columnPicUrls text not null,
          $columnComments text not null,
          $columnLikes text not null,
          $columnLikeStatuses text not null,
          $columnFollowStatuses text not null,
          $columnSenders text not null)
        ''');

      await db.execute('''
        create table $tableOrder (
          $columnOrderNo text primary key,
          $columnGoodsCode text not null,
          $columnGoodsName text not null,
          $columnPayAmount text not null,
          $columnPaidAmount text not null,
          $columnPaidCurrency text not null)
        ''');
    });
  }

  Future<int> insert(String table, Map<String, dynamic> values) async {
    return await _database.insert(table, values);
  }

  Future<List<Map<String, dynamic>>> query(String table, String where, List<dynamic> whereArgs) async {
    return await _database.query(table, where: where, whereArgs: whereArgs);
  }

  Future<int> update(String table, Map<String, dynamic> values, String where, List<dynamic> whereArgs) async {
    return await _database.update(table, values, where: where, whereArgs: whereArgs);
  }

  Future<int> delete(String table, String where, List<dynamic> whereArgs) async {
    return await _database.delete(table, where: where, whereArgs: whereArgs);
  }

  Future<void> closeDatabase() async {
    await _database.close();
  }
}
